package com.sise.cn.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

public class SendUtil {

	private static final Logger Log = LoggerFactory.getLogger(SendUtil.class);

	private final static int BUFFER_SIZE = 4096;

	public static byte[] InputStreamTOByte(InputStream in) throws IOException {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[BUFFER_SIZE];
		int count = -1;
		while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
			outStream.write(data, 0, count);
		data = null;
		return outStream.toByteArray();
	}

	public static String postJson(String destUrl,String json,boolean isDownload,String fileSuffix) {
		DataOutputStream out = null;
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		FileOutputStream outputStream = null;
		try {
            //创建连接
            URL url = new URL(destUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            connection.setRequestProperty("cookie", "Idea-4b31451f=7c7cc4eb-80f5-4e20-97f6-3fb16a4a3cc7; token=ce8e574d-7bd8-4f6e-b503-bbd9feb9e15e"); //5b841f95-0280-4831-b08a-0cbd999cd0ae
            connection.setConnectTimeout(60000);
            connection.connect();
            out = new DataOutputStream(connection.getOutputStream());
            out.write(json.getBytes("UTF-8"));
            out.flush();
            out.close();
            // 读取响应 
            
            StringBuffer sb = new StringBuffer("");
            if (isDownload) {
	            outputStream = new FileOutputStream("C:\\Users\\admin\\Desktop\\tmp\\test" + fileSuffix);
	            InputStream in = connection.getInputStream();
	            byte[] by = new byte[1024];
	            while (in.read(by) != -1) {
	            	outputStream.write(by);
	            	outputStream.flush();
	            }
            } else {
            	 reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                 String lines; 
                 while ((lines = reader.readLine()) != null) {
                     lines = URLDecoder.decode(lines, "utf-8");
                     sb.append(lines);
                 }
                 reader.close();
            }
            // 断开连接 
            connection.disconnect(); 
            return sb.toString();
        } catch (MalformedURLException e) { 
            e.printStackTrace(); 
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } finally {
        	try {
        		if (outputStream != null) outputStream.close();
				if (out != null) {out.close();}
				if (connection != null) {connection.disconnect();}
				if (reader != null) {reader.close();}
			} catch (Exception e) {
				Log.error("", e);
			}
        }
		return null;
	}
	
	public static String getJson(String destUrl) {
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		try {
            //创建连接 
            URL url = new URL(destUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("content-type","text/html,application/xhtml+xml");
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            connection.setRequestProperty("cookie", "Idea-4b31451f=7c7cc4eb-80f5-4e20-97f6-3fb16a4a3cc7; token=ce8e574d-7bd8-4f6e-b503-bbd9feb9e15e");
            connection.setConnectTimeout(60000);
            connection.connect();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = URLDecoder.decode(lines, "utf-8");
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	try {
				if (connection != null) {connection.disconnect();}
				if (reader != null) {reader.close();}
			} catch (Exception e) {
				Log.error("", e);
			}
        }
		return null;
	}
	
	public static String postUrl(String destUrl,String param) {
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		DataOutputStream out = null;
		try {
            //创建连接
            URL url = new URL(destUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("content-type","text/html,application/xhtml+xml");
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            connection.setRequestProperty("cookie", "Idea-4b31451f=7c7cc4eb-80f5-4e20-97f6-3fb16a4a3cc7; token=ce8e574d-7bd8-4f6e-b503-bbd9feb9e15e");
            connection.setConnectTimeout(60000);
            connection.connect();
            
            out = new DataOutputStream(connection.getOutputStream());
            out.write(param.getBytes("UTF-8"));
            out.flush();
            out.close();
            
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = URLDecoder.decode(lines, "utf-8");
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	try {
        		if (out != null) out.close();
				if (connection != null) {connection.disconnect();}
				if (reader != null) {reader.close();}
			} catch (Exception e) {
				Log.error("", e);
			}
        }
		return null;
	}
	
	public static String getUrl(String dest_url, String param) {
		String rec_string = "";
		URL url = null;
		HttpURLConnection urlconn = null;
		OutputStream out = null;
		BufferedReader rd = null;
		try {
			url = new URL(dest_url);
			urlconn = (HttpURLConnection) url.openConnection();
			urlconn.setReadTimeout(1000 * 5);
			urlconn.setRequestProperty("content-type","text/html,application/xhtml+xml");
			//urlconn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			//urlconn.setRequestProperty("cookie", "Idea-4b31451f=7c7cc4eb-80f5-4e20-97f6-3fb16a4a3cc7; token=ce8e574d-7bd8-4f6e-b503-bbd9feb9e15e");
			urlconn.setConnectTimeout(60000);
			urlconn.setRequestMethod("GET");
			urlconn.setDoInput(true);
			urlconn.setDoOutput(true);
			if (!StringUtils.isEmpty(param)) {
				out = urlconn.getOutputStream();
				out.write(param.getBytes("UTF-8"));
				out.flush();
				out.close();
			}
			InputStream in = urlconn.getInputStream();
			rd = new BufferedReader(new InputStreamReader(in));
			StringBuffer sb = new StringBuffer();
			int ch;
			while ((ch = rd.read()) > -1)
				sb.append((char) ch);
			rec_string = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (urlconn != null) {
					urlconn.disconnect();
				}
				if (rd != null) {
					rd.close();
				}
			} catch (Exception e) {
				Log.error("", e);
			}
		}
		return rec_string;
	}
}
